'''
处理预警数据
'''

import requests
import json
import time
import os
from logging import *

from .config import *
from .rainmeter import *

from lib.parse_time import *

def run():
    
    basicConfig(
        level=0,
        format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
        filename="log",
        filemode="a",
        encoding='UTF-8'
    )

    out = Rainmeter()
    target_ID = out["ID"]

    try:
        data = requests.get(f"https://devapi.qweather.com/v7/warning/now?key={key}&location={target_ID}")
        data = data.content.decode("UTF-8")
        data = json.loads(data)
        data['updateTime'] = reformat(data['updateTime'])
    except requests.ConnectionError:
        error(f"Disconnected from Internet")
        out["warn"] = "获取数据时失败"
        out["warncolor"] = "255,128,128,255"
        info("quit...")
        out.save()
        return
    except KeyError:
        error(f"An Error caused while getting fresh. Detail: {data}")
        out["warn"] = "获取数据时失败"
        out["warncolor"] = "255,128,128,255"
        info("quit...")
        out.save()
        return

    info("Succeed Got Refreshed Data")

    warning = ''
    color = ""

    for warns in data["warning"]:
        info(f"Warn: {warns['text']}")
        warning += warns['text'] + '#CRLF#'

    if len(data["warning"]) == 0:
        warning = "没有天气预警"
        color = "255,255,255,255"
    else:
        color = "255,64,64,255"

    out["warning"] = warning
    out["color_warning"] = color